/**
 * 预订相关JavaScript功能
 */

// 格式化时间持续时间
function calculateDuration(departureTime, arrivalTime) {
    const departure = new Date(`2000-01-01 ${departureTime}`);
    const arrival = new Date(`2000-01-01 ${arrivalTime}`);
    
    let duration = arrival - departure;
    
    // 如果到达时间小于出发时间，说明跨天了
    if (duration < 0) {
        duration += 24 * 60 * 60 * 1000; // 加一天的毫秒数
    }
    
    const hours = Math.floor(duration / (1000 * 60 * 60));
    const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
    
    return `${hours}小时${minutes}分钟`;
}

// 格式化价格
function formatPrice(price) {
    return `¥${price.toFixed(2)}`;
}

// 获取座位类型的价格
function getSeatPrice(schedule, seatClass) {
    switch(seatClass) {
        case '一等座':
            return schedule.firstClassPrice;
        case '二等座':
            return schedule.secondClassPrice;
        default:
            return schedule.secondClassPrice;
    }
}

// 验证身份证号
function validateIdCard(idCard) {
    const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    return pattern.test(idCard);
}

// 验证手机号
function validatePhone(phone) {
    const pattern = /^1[3-9]\d{9}$/;
    return pattern.test(phone);
}

// 显示加载状态
function showLoading(target) {
    $(target).html(`
        <div class="text-center py-3">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">正在加载...</p>
        </div>
    `);
}

// 显示错误信息
function showError(target, message) {
    $(target).html(`
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle me-2"></i>
            ${message}
        </div>
    `);
}

// 显示成功信息
function showSuccess(target, message) {
    $(target).html(`
        <div class="alert alert-success">
            <i class="bi bi-check-circle me-2"></i>
            ${message}
        </div>
    `);
}

// 车次查询功能
function searchSchedules(startStationId, endStationId, departureDate) {
    return new Promise((resolve, reject) => {
        if (!startStationId || !endStationId || !departureDate) {
            reject('请填写完整的查询信息');
            return;
        }

        if (startStationId === endStationId) {
            reject('出发站和到达站不能相同');
            return;
        }

        $.ajax({
            url: `/api/schedules/search?startStationId=${startStationId}&endStationId=${endStationId}&date=${departureDate}`,
            type: 'GET',
            success: function(schedules) {
                resolve(schedules);
            },
            error: function(xhr) {
                reject(xhr.responseText || '查询失败，请稍后重试');
            }
        });
    });
}

// 预订车票
function bookTicket(ticketData) {
    return new Promise((resolve, reject) => {
        // 验证数据
        if (!ticketData.passengerName || !ticketData.passengerIdCard || !ticketData.contactPhone) {
            reject('请填写完整的乘客信息');
            return;
        }

        if (!validateIdCard(ticketData.passengerIdCard)) {
            reject('身份证号格式不正确');
            return;
        }

        if (!validatePhone(ticketData.contactPhone)) {
            reject('手机号格式不正确');
            return;
        }

        $.ajax({
            url: '/api/booking',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(ticketData),
            success: function(response) {
                resolve(response);
            },
            error: function(xhr) {
                reject(xhr.responseText || '预订失败，请稍后重试');
            }
        });
    });
}

// 获取车站列表
function loadStations() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/api/stations',
            type: 'GET',
            success: function(stations) {
                resolve(stations);
            },
            error: function(xhr) {
                reject('无法加载车站数据');
            }
        });
    });
}

// 渲染车站选项
function renderStationOptions(stations, defaultText = '-- 选择车站 --') {
    let options = `<option value="">${defaultText}</option>`;
    stations.forEach(station => {
        options += `<option value="${station.id}">${station.stationName}</option>`;
    });
    return options;
}

// 渲染车次表格
function renderScheduleTable(schedules) {
    if (!schedules || schedules.length === 0) {
        return '<tr><td colspan="9" class="text-center">没有找到符合条件的车次</td></tr>';
    }

    let html = '';
    schedules.forEach(schedule => {
        const trainInfo = `${schedule.trainNumber} (${schedule.departureDate} ${schedule.departureTime})`;
        const duration = calculateDuration(schedule.departureTime, schedule.arrivalTime);
        
        html += `
            <tr>
                <td><strong>${schedule.trainNumber}</strong></td>
                <td>${schedule.startStationName}</td>
                <td>${schedule.endStationName}</td>
                <td class="text-primary">${schedule.departureTime}</td>
                <td class="text-success">${schedule.arrivalTime}</td>
                <td class="text-muted">${duration}</td>
                <td class="text-warning">${formatPrice(schedule.secondClassPrice)}</td>
                <td class="text-info">${formatPrice(schedule.firstClassPrice)}</td>
                <td>
                    <button class="btn btn-primary btn-sm book-btn"
                            data-id="${schedule.id}"
                            data-info="${trainInfo}"
                            data-second-price="${schedule.secondClassPrice}"
                            data-first-price="${schedule.firstClassPrice}">
                        <i class="bi bi-ticket me-1"></i>预订
                    </button>
                </td>
            </tr>
        `;
    });
    
    return html;
}

// 设置日期限制（只能选择今天及以后的日期）
function setDateConstraints(dateInputId) {
    const today = new Date().toISOString().split('T')[0];
    $(dateInputId).attr('min', today);
    
    // 设置默认为明天
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    $(dateInputId).val(tomorrow.toISOString().split('T')[0]);
}

// 通用的表单验证
function validateForm(formId) {
    const form = $(formId)[0];
    if (!form.checkValidity()) {
        $(formId).addClass('was-validated');
        return false;
    }
    return true;
}

// 显示确认对话框
function showConfirmDialog(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 页面加载时的初始化
$(document).ready(function() {
    // 初始化日期约束
    setDateConstraints('#departureDate');
    
    // 初始化工具提示
    if (typeof bootstrap !== 'undefined') {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
